<template>
  <el-card class="user-integral-list" style="margin: 20px;">
    <el-table :data="paginatedUsers" border style="width: 100%">
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="fullName" label="真实姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="phone" label="电话号码"></el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button @click="viewIntegralDetails(row)" size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      v-model:current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px"
    />
  </el-card>
  <!-- 积分明细弹窗 -->
  <el-dialog v-model="dialogVisible" title="积分明细" width="60%">
    <el-table :data="integralDetails" border style="width: 100%">
      <el-table-column prop="recordId" label="明细ID"></el-table-column>
      <el-table-column prop="volunteerId" label="用户ID"></el-table-column>
      <el-table-column prop="activityId" label="活动ID"></el-table-column>
      <el-table-column prop="durationHr" label="参与时长(小时)"></el-table-column>
      <el-table-column prop="points" label="积分"></el-table-column>
      <el-table-column prop="createdAt" label="创建时间"></el-table-column>
    </el-table>
  </el-dialog>

  <!-- 图表筛选按钮 -->
  <el-row justify="center" style="margin-bottom: 20px;">
    <el-button @click="loadChartData('month')">近一个月</el-button>
    <el-button @click="loadChartData('quarter')">近三个月</el-button>
    <el-button @click="loadChartData('halfYear')">近半年</el-button>
    <el-button @click="loadChartData('year')">近一年</el-button>
    <el-button @click="loadChartData('all')">所有时间</el-button>
  </el-row>

  <!-- 图表容器 -->
  <el-card class="chart-container" style="margin: 40px;">
    <h3>积分排名TOP10</h3>
    <div id="top10Chart" style="width: 100%; height: 400px;"></div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getUserList } from '@/api/user'
import { getPointRecordListByUser } from '@/api/Integral'


// 用户列表数据
const users = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const paginatedUsers = ref([])

// 积分明细数据
const integralDetails = ref([])
const selectedUserId = ref(null)
const dialogVisible = ref(false)

// 图表相关
const chartInstance = ref(null)
// 获取用户数据
const fetchUsers = async () => {
  try {
    const response = await getUserList();
    const rawData = Array.isArray(response?.data) ? response.data : [];

    const formattedUsers = rawData.map(user => ({
      userId: user.userId,
      username: user.username,
      fullName: user.fullName,
      skills: Array.isArray(user.skills) ? user.skills.map(s => s.skillName).join(', ') : '无', // 将技能数组转为逗号分隔的字符串
      email: user.email,
      phone: user.phone,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt,
      status: user.status === 0 ? '未审核' : '已审核'
    }))

    // 设置总数据
    users.value = formattedUsers;
    total.value = users.value.length;

    // 分页
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    paginatedUsers.value = users.value.slice(start, end);

  } catch (error) {
    console.error('获取用户数据失败:', error);
    users.value = [];
    paginatedUsers.value = [];
    total.value = 0;
    if(error.code == "ERR_NETWORK") {
      ElMessage.error('获取用户数据失败，请检查网络或稍后再试');
    } else if(error.response.status === 403) {
      ElMessage.error('无权限访问此页面，请重新登录');
    }
  }
}
// 分页切换
const handlePageChange = (newPage) => {
  currentPage.value = newPage
  fetchUsers()
}

// 获取积分明细数据
const fetchIntegralDetails = async (userId) => {
  try {
    const response = await getPointRecordListByUser({ userId, page: 1, size: 10 }) // 调用后端接口
    integralDetails.value = response.data || [] // 假设接口返回数据在 data 字段中
    dialogVisible.value = true
  } catch (error) {
    console.error('获取积分明细失败:', error)
    ElMessage.error('获取积分明细失败')
    integralDetails.value = []
  }
}
// 查看按钮点击事件
const viewIntegralDetails = (row) => {
  fetchIntegralDetails(row.userId)
}

// 加载图表数据
const loadChartData = async (timeRange) => {
  try {
    const response = await axios.get('/api/Integral.json')
    let rawData = Array.isArray(response.data?.data) ? response.data.data : []

    const now = new Date()

    switch (timeRange) {
      case 'month':
        rawData = rawData.filter(item => isWithinMonth(item.createTime, now))
        break
      case 'quarter':
        rawData = rawData.filter(item => isWithinThreeMonths(item.createTime, now))
        break
      case 'halfYear':
        rawData = rawData.filter(item => isWithinHalfYear(item.createTime, now))
        break
      case 'year':
        rawData = rawData.filter(item => isWithinYear(item.createTime, now))
        break
    }
    // 汇总每个用户的积分
    const userPoints = {}
    rawData.forEach(item => {
      if (!userPoints[item.userId]) {
        userPoints[item.userId] = 0
      }
      userPoints[item.userId] += item.points
    })

    // 排序并取前10名
    const sortedUserPoints = Object.entries(userPoints)
      .map(([userId, points]) => ({ userId, points }))
      .sort((a, b) => b.points - a.points)
      .slice(0, 10)

    renderChart(sortedUserPoints)
  } catch (error) {
    console.error(`加载${timeRange}数据失败:`, error)
    ElMessage.error('加载图表数据失败')
  }
}

// 时间判断函数
const isWithinMonth = (dateStr, now) => {
  const date = new Date(dateStr)
  return date >= new Date(now.getFullYear(), now.getMonth(), 1)
}
const isWithinThreeMonths = (dateStr, now) => {
  const date = new Date(dateStr)
  const threeMonthsAgo = new Date(now)
  threeMonthsAgo.setMonth(now.getMonth() - 3)
  return date >= threeMonthsAgo
}
const isWithinHalfYear = (dateStr, now) => {
  const halfYearStartMonth = now.getMonth() >= 6 ? 6 : 0
  const date = new Date(dateStr)
  return date >= new Date(now.getFullYear(), halfYearStartMonth, 1)
}
const isWithinYear = (dateStr, now) => {
  const date = new Date(dateStr)
  return date >= new Date(now.getFullYear(), 0, 1)
}

// 渲染图表
const renderChart = (data) => {
  const chartDom = document.getElementById('top10Chart')
  if (!chartDom) return

  if (chartInstance.value) {
    chartInstance.value.dispose()
  }

  chartInstance.value = echarts.init(chartDom)

  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: data.map(d => d.userId),
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [{
      name: '积分',
      type: 'bar',
      data: data.map(d => d.points),
      itemStyle: { color: '#409EFF' }
    }]
  }

  chartInstance.value.setOption(option)
}

onMounted(() => {
  fetchUsers()
   loadChartData('all') // 默认加载近一年的数据
})
</script>

<style scoped>
.user-integral-list {
  margin: 20px;
  text-align: left;
}

.chart-container {
  margin: 40px;
}
</style>